package org.praktika.api.service;

import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.praktika.api.dto.EmployeeDto;
import org.praktika.api.entity.Employee;
import org.praktika.api.repository.EmployeeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class EmployeeService {
    private final EmployeeRepository employeeRepository;
    private final PostService postService;
    private final ModelMapper modelMapper = new ModelMapper();

    @Transactional
    public EmployeeDto save(EmployeeDto employeeDto) {
        Employee employee = modelMapper.map(employeeDto, Employee.class);
       employeeRepository.save(employee);
       return modelMapper.map(employee, EmployeeDto.class);
    }

    public EmployeeDto getEmployeeDtoById(Long id) {
        return modelMapper.map(getEmloyeeById(id), EmployeeDto.class);
    }

    public Employee getEmloyeeById(Long id)  {
        Optional<Employee> employee = employeeRepository.findById(id);
        return employee.orElseThrow(() -> new RuntimeException("No employee found"));
    }

    @Transactional
    public EmployeeDto updateEmployee(EmployeeDto employeeDto)  {
        Employee employee = getEmloyeeById(employeeDto.getId());
        employee.setFullName(employeeDto.getFullName());
        employee.setLogin(employeeDto.getLogin());
        employee.setPost(postService
                .getById(employeeDto.getPost().getId()));
        employeeRepository.save(employee);
        return modelMapper.map(employee, EmployeeDto.class);
    }

    public List<EmployeeDto> findAllEmployee() {
        List<Employee> employees = employeeRepository.findAll();
        List<EmployeeDto> employeesDto = new ArrayList<>();
        for (Employee employee : employees) {
            employeesDto.add(modelMapper.map(employee, EmployeeDto.class));
        }
        return employeesDto;
    }

    @Transactional
    public void deleteEmployee(Long id) {
        employeeRepository.deleteById(id);
    }
}
